package com.diandian.ddop;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.diandian.common.Constant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @description DdOpFilter
 * @author TDW
 * @date 2016年12月29日
 *
 */
public class DdOpFilter extends ZuulFilter/*BaseZullFilter*/ {
	
	/** log4j */
//    private static final Logger log = Logger.getLogger(DdOpFilter.class);
    private static final Logger logger = LogManager.getLogger(DdOpFilter.class.getName());  
    /** 灰度环境ddop serverId */
    private static final String GRAY_DDOP_SERVER_ID = "gray_dd_op";
    /** ddop正式环境serverId */
    private static final String DDOP_SERVER_ID = "dd_op";
    
    
    public boolean shouldFilter() {
        return true;
    }

    @Resource
    private JdbcTemplate jdbcTemplate;

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        String uri = req.getRequestURI();
        String appId = uri.split("/")[1];//
        if (appId.equalsIgnoreCase(Constant.op)) {
        	logger.info("#####request dd_op ："+uri);
        	if(uri.indexOf(Constant.URL_PRINTER_SYNC) != -1){//打印机下发
        		setToService(ctx, req);
        	}else if(uri.indexOf(Constant.URL_ORDER_REPRINTER) != -1){//PC端订单重打： 厨打、小票、标签、全部重打
        		String shopId = req.getParameter("shop_id");
        		final String orderId = req.getParameter("order_id");
        		//适配处理
        		if(StringUtils.isBlank(shopId)){
        			try{
	        			shopId = jdbcTemplate.queryForObject("select shop_id from orderlist where id=?",new Object[]{orderId}, new RowMapper<String>() {
							public String mapRow(ResultSet rs, int arg1) throws SQLException {
								if(rs == null)
									throw new RuntimeException("无此订单数据，order_id: "+orderId);
								Long s = rs.getLong("shop_id");
								return s+"";
							}
						});
        			}catch(Exception e){
        				logger.error(e);
        				throw new RuntimeException("无此订单数据，order_id: "+orderId);//统一交给异常拦截器处理
        			}
        		}
        		logger.info("###是否是灰度商家({})："+Constant.grayshops.contains(shopId),shopId);
        		if(Constant.grayshops.contains(shopId)){
        			ctx.set("serviceId", GRAY_DDOP_SERVER_ID);
        		}else{
        			ctx.set("serviceId", DDOP_SERVER_ID);
        		}
        	}else if(uri.indexOf(Constant.URL_APP_ORDER_REPRINTER) != -1){//APP订单重打
        		setToService(ctx, req);
        	}else if(uri.indexOf(Constant.URL_SEND_SHOP_CONF) != -1){//商家配置下发 
        		setToService(ctx, req);
        	}else if(uri.indexOf(Constant.URL_SEND_TEST_ORDER) != -1){//测试单下发
        		setToService(ctx, req);
        	}else if(uri.indexOf(Constant.URL_ORDER_REPRINTER) != -1){//订单重发 
        		setToService(ctx, req);
        	}else{
        		ctx.set("serviceId", DDOP_SERVER_ID);
        	}
        }
        //int a = 1/0;// Error Filter test
        return null;
    }


    
    /**
     * @description setToService 路由到对应的服务器上
     * @param ctx
     * @param req
     * @author TDW
     * @date 2016年12月29日
     * @modify_date 
     * @modify_author
     * @modify_desc
     */
	private void setToService(RequestContext ctx, HttpServletRequest req) {
		String shopId = req.getParameter("shop_id");
		logger.info("是否是灰度商家："+Constant.grayshops.contains(shopId));
		if(Constant.grayshops.contains(shopId)){//灰度商家列表
			ctx.set("serviceId", GRAY_DDOP_SERVER_ID);
		}else{
			ctx.set("serviceId", DDOP_SERVER_ID);
		}
	}


    public String filterType() {
        return "pre";
    }


    public int filterOrder() {
        return 0;
    }

}

